package com.huatai.exchange.load;

import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.ListUtils;
import com.faneui.dal.DBUtils;
import com.faneui.dbf.model.DBFObject;
import com.faneui.dbf.utils.DBFUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.huatai.exchange.dal.model.ExcFileLoadInfo;
import com.linuxense.javadbf.DBFField;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service("dataDbfFileLoadService")
public class DataDbfFileLoadServiceImpl extends AbstractDataFileLoadService {

    private Map<String,String> sqlMap = Maps.newConcurrentMap() ;

    @Override
    public void loadDataInDataBase(ExcFileLoadInfo loadInfo,List<String> fileNames ,String filePath,Map<String, Object> resvMap) throws BusinessException {
        String occurDate =  (String) resvMap.get("YYYYMMDD");
        // 数据库数据备份
        String tableName = loadInfo.getTableName();

        String deleteSql = sqlMap.get(tableName + "_delete");
        String insertSql = sqlMap.get(tableName + "_insert");
        List<Object[]> dataList = Lists.newArrayList();
        for (String fileName : fileNames) {
            DBFObject dbfObject =  DBFUtils.readDBF(filePath+ fileName);
            if (StringUtils.isBlank(deleteSql) || StringUtils.isBlank(insertSql)) {
                StringBuilder columnSql = new StringBuilder();
                StringBuilder valueSql = new StringBuilder();
                for (DBFField dbfField : dbfObject.getFields()) {
                    String fieldName = "BY".equalsIgnoreCase(dbfField.getName()) ? "BYBY" : dbfField.getName();
                    columnSql.append(",").append(fieldName);
                    valueSql.append(",?");
                }
                insertSql = "insert into " + tableName + "(occur_date" + columnSql.toString() + ")values(?" + valueSql.toString() + ")";
                deleteSql = "delete " + tableName + " where occur_date = ? ";
                sqlMap.put(tableName + "_insert", insertSql);
                sqlMap.put(tableName + "_delete", deleteSql);
            }
            if (dbfObject.getData() != null && dbfObject.getData().length != 0) {
                for (Object o : dbfObject.getData()) {
                    List<Object> oList = Lists.newArrayList();
                    oList.add(occurDate);
                    oList.addAll(Lists.newArrayList((Object[]) o));
                    dataList.add(oList.toArray());
                }
            }
        }
        DBUtils.execute(localConnection.getConn(), deleteSql, occurDate);
        if(ListUtils.isNotEmpty(dataList))
            DBUtils.insertBatch(localConnection.getConn(), insertSql, dataList);
    }

}
